<template>
  <div class="app-container">

    <!-- 查询和其他操作 -->
    <div class="filter-container">
      <el-form :inline="true">
        <el-form-item label="角色名称">
          <el-input v-model="listQuery.name" clearable class="filter-item" placeholder="角色名称"/>
        </el-form-item>
        <el-button class="filter-item" type="primary" icon="el-icon-search" @click="handleFilter">查找</el-button>
        <el-button
          v-hasPermi="['admin:sys:role:create']"
          class="filter-item"
          style="float:right"
          type="primary"
          icon="el-icon-plus"
          @click="startAdd">添加</el-button>
      </el-form>
    </div>

    <!-- 查询结果 -->
    <el-table v-loading="listLoading" :data="list" element-loading-text="正在查询中。。。" border fit highlight-current-row >

      <el-table-column align="center" label="角色名称" prop="name" />

      <el-table-column align="center" label="角色说明" prop="remark"/>
      <el-table-column label="状态" align="center" width="100">
        <template v-hasPermi="['admin:sys:role:updateStatus']" slot-scope="{row}">
          <el-switch
            v-if="row.superAdminFlag !== 1"
            v-model="row.dataStatus"
            :active-value="1"
            :inactive-value="2"
            @change="handleStatusChange(row)"
          />
        </template>
      </el-table-column>
      <el-table-column align="center" label="创建时间" prop="createTime"/>

      <el-table-column align="center" label="操作" width="180" class-name="small-padding fixed-width">
        <template slot-scope="{row}">
          <el-button
            v-hasPermi="['admin:sys:role:update']"
            v-if="row.superAdminFlag !== 1"
            type="primary"
            size="small"
            @click="startEditAdmin(row)">编辑</el-button>
            <!-- <el-button type="primary" size="small"
           v-if="row.superAdminFlag !== 1"
            v-hasPermi="['admin:sys:role:delete']"
          @click="deleteAdminFunc(row.name, row.id)">删除</el-button> -->
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="listQuery.page"
      :limit.sync="listQuery.pageSize"
      @pagination="getList" />

    <el-dialog :close-on-click-modal="false" :title="dialogType == 1?'新增角色':'修改角色'" :visible.sync="dialogFormVisible" width="28%">
      <el-form ref="dialogForm" :rules="formRules" :model="dialogForm" label-width="120px">

        <el-form-item label="角色名称" prop="name">
          <el-input v-model="dialogForm.name" clearable placeholder=""/>
        </el-form-item>
        <el-form-item label="角色说明" prop="remark">
          <el-input v-model="dialogForm.remark" type="textarea" clearable placeholder=""/>
        </el-form-item>

        <el-form-item label="菜单权限" prop="menuIdList">
          <el-checkbox v-model="menuExpand" @change="handleCheckedTreeExpand($event, 'menu')">展开/折叠</el-checkbox>
          <el-checkbox v-model="menuNodeAll" @change="handleCheckedTreeNodeAll($event, 'menu')">全选/全不选</el-checkbox>
          <el-checkbox v-model="dialogForm.menuCheckStrictly" @change="handleCheckedTreeConnect($event, 'menu')">父子联动</el-checkbox>
          <el-tree
            ref="menu"
            :data="menuList"
            :props="defaultProps"
            @check="menuCheck"
            :check-strictly="!dialogForm.menuCheckStrictly"
            class="tree-border"
            empty-text="加载中，请稍候"
            show-checkbox
            node-key="id"/>
        </el-form-item>
        <el-form-item label="数据权限" prop="parkIdList">
          <el-checkbox v-model="deptExpand" @change="handleCheckedTreeExpand($event, 'dept')">展开/折叠</el-checkbox>
          <el-checkbox v-model="deptNodeAll" @change="handleCheckedTreeNodeAll($event, 'dept')">全选/全不选</el-checkbox>
          <!-- <el-checkbox v-model="dialogForm.deptCheckStrictly" @change="handleCheckedTreeConnect($event, 'dept')">父子联动</el-checkbox> -->
          <div id="tree">
            <el-tree
              ref="dept"
              :data="permissionsData"
              :props="parkDefaultProps"
              :check-strictly="!dialogForm.deptCheckStrictly"
              empty-text="加载中，请稍候"
              class="tree-border"
              show-checkbox
              node-key="id"/>
          </div>
        </el-form-item>
      </el-form>

      <div slot="footer" class="dialog-footer" align="center">
        <el-button @click="confirmEdit('dialogForm')">确定</el-button>
        <el-button @click="dialogFormVisible = false">取消</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
/* eslint-disable eqeqeq */

import { listRole, createRole, detailRole, updateRole, findUserRoles, findRoleParks,
  updateStatus, rolelistRolePark, rolelistRoleMenu } from '@/api/permission/role'
import Pagination from '@/components/Pagination' // Secondary package based on el-pagination
import { menuList } from '@/api/permission'
export default {
  name: 'Admin',
  components: { Pagination },
  data() {
    return {
      menuExpand: false,
      menuNodeAll: false,
      deptExpand: false,
      deptNodeAll: false,
      list: null, // 列表数据
      total: 0, // 总数
      listLoading: true, // 表格加载
      listQuery: {// 请求参数
        page: 1,
        pageSize: 10
      },
      downloadLoading: false,
      dialogFormVisible: false,
      dialogForm: {},
      dialogType: 1,
      formRules: {
        name: [{ required: true, message: '角色名称不能为空', trigger: 'blur' }],
        menuIdList: [{ required: true, message: '菜单权限不能为空', trigger: 'blur' }]
        // parkIdList: [{ required: true, message: '数据权限不能为空', trigger: 'change' }],
      },
      defaultProps: {
        children: 'children',
        label: 'title'
      },
      parkDefaultProps: {
        children: 'parkList',
        label: 'name',
        disabled: (data, node) => {
          if (node.level == 1) {
            return true
          } else {
            return false
          }
        }
      },
      menuList: [], // 菜单数据
      permissionsData: []// 数据权限
    }
  },
  created() {
    this.getList()
  },
  methods: {
    menuCheck(){//
      let dialogForm = {...this.dialogForm}
      dialogForm.menuIdList = this.getMenuAllCheckedKeys()
      this.dialogForm = {...dialogForm}
    },
    // 树权限（展开/折叠）
    handleCheckedTreeExpand(value, type) {
      if (type == 'menu') {
        const treeList = this.menuList
        for (let i = 0; i < treeList.length; i++) {
          this.$refs.menu.store.nodesMap[treeList[i].id].expanded = value
        }
      } else if (type == 'dept') {
        const treeList = this.permissionsData
        for (let i = 0; i < treeList.length; i++) {
          this.$refs.dept.store.nodesMap[treeList[i].id].expanded = value
        }
      }
    },
    // 树权限（全选/全不选）
    handleCheckedTreeNodeAll(value, type) {
      if (type == 'menu') {
        this.$refs.menu.setCheckedNodes(value ? this.menuList : [])
      } else if (type == 'dept') {
        console.log(value)
        this.$refs.dept.setCheckedNodes(value ? this.permissionsData : [])
      }
    },
    // 树权限（父子联动）
    handleCheckedTreeConnect(value, type) {
      if (type == 'menu') {
        this.dialogForm.menuCheckStrictly = !!value
      } else if (type == 'dept') {
        this.dialogForm.deptCheckStrictly = !!value
      }
    },
    // 角色状态修改
    handleStatusChange(row) {
      const text = row.dataStatus == 1 ? '启用' : '停用'
      this.$confirm('确认要"' + text + '""' + row.name + '"角色吗？', '温馨提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        updateStatus({ id: row.id, dataStatus: row.dataStatus }).then(response => {
          this.$message({
            message: text + '成功',
            type: 'success'
          })
          this.getList()
        })
      }).catch(() => {
        row.dataStatus = row.dataStatus == 2 ? 1 : 2
      })
    },
    // 所有菜单节点数据
    getMenuAllCheckedKeys() {
      // 目前被选中的菜单节点
      const checkedKeys = this.$refs.menu.getCheckedKeys()
      // 半选中的菜单节点
      const halfCheckedKeys = this.$refs.menu.getHalfCheckedKeys()
      checkedKeys.unshift.apply(checkedKeys, halfCheckedKeys)
      return checkedKeys
    },
    // 所有停车节点数据
    getDeptAllCheckedKeys() {
      // 目前被选中的停车节点
      const checkedKeys = this.$refs.dept.getCheckedKeys()
      // 半选中的停车节点
      const halfCheckedKeys = this.$refs.dept.getHalfCheckedKeys()
      checkedKeys.unshift.apply(checkedKeys, halfCheckedKeys)
      return checkedKeys
    },
    // 表单重置
    reset() {
      if (this.$refs.menu != undefined) {
        this.$refs.menu.setCheckedKeys([])
      }
      if (this.$refs.dept != undefined) {
        this.$refs.dept.setCheckedKeys([])
      }
      this.menuExpand = false,
      this.menuNodeAll = false,
      this.deptExpand = false,
      this.deptNodeAll = false,
      this.dialogForm = {
        menuCheckStrictly: true,
        deptCheckStrictly: true
      }
      // this.resetForm("dialogForm");
    },
    async getFindRoleParks() { // 数据权限数据
      const response = await rolelistRolePark()
      const data1 = response.data || []
      this.permissionsData = data1.map(item => {
        return {
          ...item,
          disabled: true
        }
      })
    },
    async getMenuList() { // 菜单数据
      const response = await rolelistRoleMenu()
      const data1 = response.data || []
      this.menuList = data1
    },
    getList() { // 获取页面列表数据
      this.listLoading = true
      listRole(this.listQuery).then(response => {
        const data1 = response.data || {}
        const list = data1.list || []
        this.list = list
        this.total = data1.total
        this.listLoading = false
      })
    },
    handleFilter() {
      this.listQuery.page = 1
      this.getList()
    },
    deleteAdminFunc(username, id) {
      this.$confirm(`您确定删除账号：${username}`, '温馨提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        detailRole(id).then(response => {
          this.$message({
            message: '删除成功!',
            type: 'success'
          })
          this.getList()
        })
      })
    },
    startAdd() { // 新增
      this.reset()
      this.getMenuList()
      this.getFindRoleParks()
      this.dialogFormVisible = true
      this.dialogType = 1
      this.$nextTick(() => {
        this.$refs.dialogForm.clearValidate()
      })
    },

    confirmEdit(formName) {
      console.log(this.getMenuAllCheckedKeys())
      this.dialogForm.menuIdList = this.getMenuAllCheckedKeys()
      let parkIdList = this.getDeptAllCheckedKeys()
      console.log('this.dialogForm.parkIdList', this.dialogForm)
      parkIdList = parkIdList.filter(item => {
        return !this.permissionsData.some(i => item == i.id)
      })
      this.dialogForm.parkIdList = [...parkIdList]
      this.$refs[formName].validate((valid) => {
        if (valid) {
          if (this.dialogType == 1) {
            createRole(this.dialogForm).then(response => {
              this.$message({
                message: '添加成功!',
                type: 'success'
              })
              this.getList()
              this.dialogFormVisible = false
              this.dialogForm = {}
            })
          } else {
            updateRole(this.dialogForm).then(response => {
              this.$message({
                message: '修改成功!',
                type: 'success'
              })
              this.getList()
              this.dialogFormVisible = false
              this.dialogForm = {}
            })
          }
        }
      })
    },
    startEditAdmin(row) { // 修改
      this.reset()
      detailRole(row.id).then(async response => {
        const data1 = response.data || {}
        this.dialogFormVisible = true
        this.dialogType = 2
        this.$nextTick(() => {
          this.$refs.dialogForm.clearValidate()
        })
        this.dialogForm = { ...data1, menuCheckStrictly: true, deptCheckStrictly: true }
        await this.getMenuList()
        console.log(data1.menuIdList)
        data1.menuIdList.forEach((v) => {
          this.$nextTick(() => {
            this.$refs.menu.setChecked(v, true, false)
          })
        })
        await this.getFindRoleParks()
        data1.parkIdList.forEach((v) => {
          this.$nextTick(() => {
            this.$refs.dept.setChecked(v, true, false)
          })
        })
      })
    }

  }

}
</script>
<style lang="scss" scoped>
/deep/ .tree-border{
  border:1px solid #f2f2f2;
  border-radius: 5px;
}
#tree{
   /deep/ .el-tree-node__content{
     .el-checkbox{display: none;}

   }
   /deep/.el-tree-node__children{
     .el-checkbox{display: block;}
   }
}

</style>
